import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:untitled1/app/utils/utilJson.dart';
import 'package:untitled1/app/utils/utilRouter.dart';
import 'package:untitled1/app/utils/utilStr.dart';
import 'package:untitled1/app/widgets/TitleBar.dart';
import 'package:untitled1/app/widgets/base_page/BaseStatefulPage.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:url_launcher/url_launcher.dart';


class WebViewPage extends BaseStatefulPage {
  var url = 'https://www.jd.com/?cu=true';
   var  webpageName='';
   // var  titleIsHidden=false;
   // String static= '';
  WebViewPage({required this.url,required this.webpageName});

  @override
  BaseStatefulPageState<BaseStatefulPage> createState() {
    return _WebViewPageState();
  }
 }
 class _WebViewPageState extends BaseStatefulPageState<WebViewPage> {
   late final WebViewController _controller;
   String currentVersion = "1";  // 当前版本号
  @override
  void initState() {
    super.initState();
    print(">]url="+widget.url);

    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
    //js调用dart代码，给浏览器window注册MyChannel对象
      ..addJavaScriptChannel('MyChannel', onMessageReceived: (JavaScriptMessage message) {
        print(">]收到 Vue 消息: ${message.message}");
        jsClick(message.message);

        // 把数据传给浏览器
        _controller.runJavaScript("fromFlutter('收到你说的：${message.message}')");
      })
      ..setNavigationDelegate(
        NavigationDelegate(
          onNavigationRequest: (NavigationRequest request) async {
            final uri = Uri.parse(request.url);

            // ✅ 如果是 http 或 https，正常加载
            if (uri.scheme == 'http' || uri.scheme == 'https') {
              return NavigationDecision.navigate;
            }

            // ❗ 处理 tel:, mailto:, intent:, weixin: 等 Scheme
            if (await canLaunchUrl(uri)) {
              await launchUrl(uri, mode: LaunchMode.externalApplication);
              return NavigationDecision.prevent;
            }

            // ❗ 默认阻止无法识别的 scheme
            return NavigationDecision.prevent;
          },
          onPageStarted: (url) => print("开始加载: $url"),
          onPageFinished: (url) => print("加载完成: $url"),
          onWebResourceError: (error) =>
              print("网页出错: ${error.description}"),
        )
    );

    final cleanUrl = widget.url.trim(); // 去除首尾空格
    _controller.loadRequest(Uri.parse(cleanUrl));
    // _controller.load
    // _loadPageWithCache(widget.url);
  }
   // 加载页面并控制缓存

   @override
  Widget buildPage(BuildContext context) {
    return Scaffold(
      // appBar: widget.titleIsHidden?TitleBar(title: '${widget.webpageName}'):null,
      body:  Container(
        width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          color: Colors.white,
          child:Column(
        children: [
          SizedBox(height: 50),
          Expanded(
            child: WebViewWidget(
              controller: _controller,
            ),
          ),
          // Text('当前版本号：$currentVersion'),
        ],
      )),
    );
  }

  void jsClick(data){
    print(">]jsClick="+data);
    Map<String, dynamic> map= utilJson.strToMap(data);
    print(">]map=${map}---type=${map['type']}");
    if(map['type']==1){
      utilRouter.back();
    }
  }

}